package com.ymy.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianfeng.util.ResultMsg;
import com.ymy.entity.TbSpeedkill;
import com.ymy.mapper.SpeedkillMapper;
import com.ymy.service.SpeedkillService;
import com.ymy.util.DateUtil;

import com.ymy.util.RedisKey;
import org.aspectj.weaver.IUnwovenClassFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.List;
@Service
public class SpeedkillServiceImpl extends ServiceImpl<SpeedkillMapper, TbSpeedkill> implements SpeedkillService {
    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public ResultMsg showdateMenu() {
        List<Date> dataMenus = DateUtil.getDateMenus();
        return ResultMsg.success(dataMenus);
    }

    @Override
    public ResultMsg showGoods(TbSpeedkill tbSpeedkill) {
        //redis 中获得已经缓存过的数据
        List values = redisTemplate.opsForHash().values(RedisKey.SPEED_KILL_GOODS + DateUtil.date2Str(tbSpeedkill.getSpeedStarttime()));
        return ResultMsg.success(values);
    }

    @Override
    public ResultMsg speedkill(TbSpeedkill tbSpeedkill) {
        //redis中查 RedisKey.SPEED_KILL_GOODS+起始时间段---gid--秒杀商品
        String starttime = DateUtil.date2Str(tbSpeedkill.getSpeedStarttime());
        Object o = redisTemplate.opsForHash().get(RedisKey.SPEED_KILL_GOODS + starttime, tbSpeedkill.getGoodsId().toString());
        TbSpeedkill tbSpeedkill1 = JSONObject.parseObject(JSONObject.toJSONString(o), TbSpeedkill.class);
        //更改秒杀的数量-1
        if (tbSpeedkill1.getSpeedNum()<=0)
            return ResultMsg.error(777,"商品数量不足，抢购失败");
        //RedisKey.SPEED_KILL_GOODS_STOCk+gid
        tbSpeedkill1.setSpeedNum(tbSpeedkill1.getSpeedNum()-1);
        redisTemplate.opsForHash().put(RedisKey.SPEED_KILL_GOODS + starttime,tbSpeedkill.getGoodsId().toString(),tbSpeedkill1);
        //更改库存数量-1
        redisTemplate.boundValueOps(RedisKey.SPEED_KILL_GOODSTOCK + tbSpeedkill1.getGoodsId().toString()).decrement();
                            return ResultMsg.success();
    }


}
